#!/usr/bin/env python
import sys

import json

from tornado.web import Application, RequestHandler
from tornado.httpserver import HTTPServer
from tornado.options import define, options, parse_command_line
from tornado.ioloop import IOLoop

define("port", default=9999, type=int)

class ExampleHandler(RequestHandler):

    def get(self):
        self.render('templates/index.html')

class UploadHtmlHandler(RequestHandler):

    def post(self):
        with open('templates/index.html', 'w+') as f:
            f.write(self.get_argument('html_body'))
        self.write({'state' : '200'})

class MyApplication(Application):

    def __init__(self):
        handlers = [
            (r'/', ExampleHandler),
            (r'/upload_html', UploadHtmlHandler),
        ]
        settings = dict()
        Application.__init__(self, handlers, settings)

def create_server():
    parse_command_line()
    http_server = HTTPServer(MyApplication())
    http_server.listen(options.port)
    IOLoop.instance().start()

if __name__ == "__main__":
    try:
        create_server()
    except KeyboardInterrupt, e:
        print "Cancelled by user type Ctrl+c."
        sys.exit(0)
